package com.study.notepad.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        doPost(request, response);

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        String method = request.getRequestURI();

        int i = method.lastIndexOf("/");
        method = method.substring(i + 1);

        Method m = null;
        try {
            //3.获取当前类中名字为 method 的方法
            m = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //4.调用  method 方法
            m.invoke(this, request, response);

        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            redirect("/404.jsp", request, response);
        }
    }

    public void redirect(String url, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.sendRedirect(request.getContextPath() + url);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void forward(String url, HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getRequestDispatcher(  url).forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }
}